using B.S.XZYData.Api.Wrter.Application.Command.WorkTask;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Transactions;

namespace B.S.XZYData.Api.Wrter.Application.Handler.WorkTask
{
    /// <summary>
    /// 更新任务处理器
    /// </summary>
    public class UpdateWorkTaskHandler : IRequestHandler<UpdateWorkTaskCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Domain.ZSHH.Task> _taskRepo;
        private readonly ILogger<UpdateWorkTaskHandler> _logger;

        public UpdateWorkTaskHandler(
            IBaseRepository<Domain.ZSHH.Task> taskRepo,
            ILogger<UpdateWorkTaskHandler> logger)
        {
            _taskRepo = taskRepo;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(UpdateWorkTaskCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            try
            {
                // 验证任务是否存在
                var existingTask = await _taskRepo.GetValue(request.Id);
                if (existingTask == null || existingTask.IsDeleted)
                {
                    res.Msg = "任务不存在";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                // 更新任务信息
                existingTask.ProcessId = request.ProcessId;
                existingTask.AllocationList = request.AllocationList;
                existingTask.PlannedStartTime = request.PlannedStartTime;
                existingTask.PlannedEndTime = request.PlannedEndTime;
                existingTask.PlannedQuantity = request.PlannedQuantity;
                existingTask.GoodQuantity = request.GoodQuantity;
                existingTask.DefectiveQuantity = request.DefectiveQuantity;
                existingTask.ActualStartTime = request.ActualStartTime;
                existingTask.ActualEndTime = request.ActualEndTime;
                existingTask.Updator = request.Updator;
                existingTask.UpdatorDate = DateTime.Now;

                var result = await _taskRepo.UpdateAsync(existingTask);
                if (result <= 0)
                {
                    res.Msg = "更新任务失败";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                res.Data = result;
                res.Code = ApiEnum.Success;
                res.Msg = "更新任务成功";

                _logger.LogInformation($"更新任务成功，任务ID：{request.Id}");
                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"更新任务异常：{ex.Message}");
                res.Msg = "更新任务异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }
    }
} 